import requests
import json
import sys
import hashlib
import time
import random

class YouDao():

    def __init__(self, word):
        self.url = "https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
        self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36",
                        "Cookie": "OUTFOX_SEARCH_USER_ID=2146277762@10.169.0.83; JSESSIONID=aaaPU95IX5TK-gvNm-2Rx; \
                        OUTFOX_SEARCH_USER_ID_NCOO=374810669.17275906; fanyi-ad-id=113723; fanyi-ad-closed=1; \
                        ___rl__test__cookies=1627652652196",
                        "Referer": "https://fanyi.youdao.com/"}
        self.word = word

    def get_salt(self):
        salt = int(time.time()*1000) + random.randint(0,10)
        return salt

    def get_md5(self, v):
        md5 = hashlib.md5()
        md5.update(v.encode("utf-8"))
        value = md5.hexdigest()
        return value

    def get_sign(self, key, salt):
        sign = "fanyideskweb" + key + str(salt) + "Y2FYu%TNSbMCxc3t2u^XT"
        sign = self.get_md5(sign)
        return sign

    def get_data(self):
        # session = requests.session()
        # session.get("https://fanyi.youdao.com/")
        resp = requests.post(self.url, headers=self.headers, data=self.get_request_params())
        return resp

    def parse_data(self):
        data = self.get_data().content.decode()
        data_dict = json.loads(data)
        # print(data_dict)
        content = data_dict["translateResult"][0][0]['tgt']
        return content

    def get_request_params(self):
        salt = self.get_salt()
        sign = self.get_sign(self.word, salt)
        lts = int(time.time()*1000)
        form_data = {
            "i": self.word,
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            "salt": salt,
            "sign": sign,
            "lts": lts,
            "bv": "24ecb70ba6203e4453baed50aa26b78e",
            "doctype": "json",
            "version": '2.1',
            "keyfrom": "fanyi.web",
            "action":  "FY_BY_REALTIME"
        }
        return form_data

    def run(self):
        # session = requests.session()
        # self.parse_data()
        res = self.parse_data()
        print(res)

if __name__ == "__main__":
    word = input("请输入要翻译的内容: ")
    youdao = YouDao(word)
    youdao.run()